<template>
  <a-drawer
    title="新增商铺"
    :maskClosable="false"
    width=750
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="shopAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form">
      <a-form-item label='商铺编码' v-bind="formItemLayout">
        <a-input v-decorator="['shopCode',
                   {rules: [
                    { required: true, message: '商铺编码不能为空'},
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='商铺名称' v-bind="formItemLayout">
        <a-input v-decorator="['shopName',
                   {rules: [
                    { required: true, message: '商铺名称不能为空'},
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='所属片区' v-bind="formItemLayout">
        <a-input-search v-decorator="['areaName',
                   {rules: [
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"
                  enter-button="搜索"
                  @search="showAreaSearch">
        </a-input-search>
      </a-form-item>
      <a-form-item label='街道' v-bind="formItemLayout">
        <a-input v-decorator="['street',
                   {rules: [
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='具体地址' v-bind="formItemLayout">
        <a-input v-decorator="['shopAdr',
                   {rules: [
                    { max: 50, message: '长度不能超过50个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='产权人姓名' v-bind="formItemLayout">
        <a-input-search v-decorator="['ownerName',
                   {rules: [
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"
                  enter-button="搜索"
                  @search="showOwnerSearch">
        </a-input-search>
      </a-form-item>
      <a-form-item label='经营人姓名' v-bind="formItemLayout">
        <a-input-search v-decorator="['opeName',
                   {rules: [
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"
                  enter-button="搜索"
                  @search="showOpeSearch">
        </a-input-search>
      </a-form-item>
      <a-form-item label='经营类型' v-bind="formItemLayout">
        <a-input v-decorator="['opeType',
                   {rules: [
                    { max: 20, message: '长度不能超过20个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='年租金' v-bind="formItemLayout">
        <a-input-number style="width: 100%" v-decorator="['rent']"
                        :min="0"
                        :max="9999999999"
                        />
      </a-form-item>
      <a-form-item label='年经营收入' v-bind="formItemLayout">
        <a-input-number style="width: 100%" v-decorator="['revenue']"
                        :min="0"
                        :max="9999999999"
                        />
      </a-form-item>
      <a-form-item
      v-for="(k, index) in form.getFieldValue('taxInfos')"
      :key="k"
      v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
      :required="false"
      :label="index === 0 ? '纳税信息' : ''"
      >
        <!-- <a-input-number style="width: 100%" v-decorator="['revenue']"
                        :min="0"
                        :max="9999999999"
                        :precision="0.01"/> -->
        <a-input-group compact style="width: 90%">
          <a-input-number
          v-decorator="[
            `taxYear[${k}]`
          ]"
          placeholder="请输入年份"
          :min="2000"
          :max="2030"
          :precision="0"
          style="width: 40%" />
          年
          <a-input-number
          v-decorator="[
            `taxSum[${k}]`
          ]"
          placeholder="请输入年纳税额"
          :min="0"
          :max="9999999999"
          style="width: 40%" />
          元
        </a-input-group>
        <a-icon
          v-if="form.getFieldValue('taxInfos').length > 1"
          class="dynamic-delete-button"
          type="minus-circle-o"
          :disabled="form.getFieldValue('taxInfos').length === 1"
          @click="() => removeTax(k)"
        />
      </a-form-item>
      <a-form-item v-bind="formItemLayoutWithOutLabel">
        <a-button type="dashed" style="width: 60%" @click="addTax">
          <a-icon type="plus" /> 增加纳税信息
        </a-button>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
    <!-- 查询用户 -->
    <rs-search
      @close="handleRsSearchClose"
      @success="handleRsSearchSuccess"
      :searchType="searchType"
      :ownerVisible="rsSearch.ownerVisible">
    </rs-search>
    <!-- 区域查询 -->
    <area-search
      @close="handleAreaSearchClose"
      @success="handleAreaSearchSuccess"
      :areaVisible="areaSearch.areaVisible">
    </area-search>
  </a-drawer>
</template>
<script>
import RsSearch from './RsSearch'
import AreaSearch from './AreaSearch'
let id = 1
const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'ShopAdd',
  components: {RsSearch, AreaSearch},
  props: {
    shopAddVisiable: {
      default: false
    }
  },
  data () {
    return {
      loading: false,
      formItemLayout,
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 18, offset: 3 }
        }
      },
      // form: this.$form.createForm(this),
      tShop: {},
      searchType: '',
      rsSearch: {
        ownerVisible: false,
        ownerId: '',
        opeId: ''
      },
      areaSearch: {
        areaVisible: false,
        areaId: ''
      }
    }
  },
  methods: {
    reset () {
      this.loading = false
      this.tShop = {}
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.setShopFields()

          const keys = this.form.getFieldValue('taxInfos')
          const taxSum = this.form.getFieldValue('taxSum') || []
          const taxYear = this.form.getFieldValue('taxYear') || []
          this.tShop.taxInfos = []
          keys.forEach(item => {
            if ((taxSum[item] !== null && taxSum[item] !== undefined) && (taxYear[item] !== null && taxYear[item] !== undefined)) {
              this.tShop.taxInfos.push({
                taxSum: taxSum[item],
                taxYear: taxYear[item]
              })
            }
          })

          this.loading = true
          this.$post('tShop', {
            ...this.tShop,
            ownerId: this.rsSearch.ownerId,
            opeId: this.rsSearch.opeId,
            areaId: this.areaSearch.areaId
          }).then(() => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    setShopFields () {
        let values = this.form.getFieldsValue(['shopName', 'shopCode', 'areaName', 'street', 'shopAdr', 'ownerName', 'opeName', 'opeType', 'rent', 'revenue'])
        if (typeof values !== 'undefined') {
            Object.keys(values).forEach(_key => { this.tShop[_key] = values[_key] })
        }
    },
    handleRsSearchClose () {
      this.rsSearch.ownerVisible = false
      this.searchType = ''
    },
    handleRsSearchSuccess (rs, searchType) {
      this.searchType = ''
      this.rsSearch.ownerVisible = false
      if (searchType === '产权人') {
        this.form.setFieldsValue({
          ownerName: rs.rsName || rs.cardId
        })
        this.rsSearch.ownerId = rs.id || ''
      } else if (searchType === '经营人') {
        this.form.setFieldsValue({
          opeName: rs.rsName || rs.cardId
        })
        this.rsSearch.opeId = rs.id || ''
      }
    },
    showOwnerSearch () {
      this.searchType = '产权人'
      this.rsSearch.ownerVisible = true
    },
    showOpeSearch () {
      this.searchType = '经营人'
      this.rsSearch.ownerVisible = true
    },
    showAreaSearch () {
      this.areaSearch.areaVisible = true
    },
    handleAreaSearchClose () {
      this.areaSearch.areaVisible = false
    },
    handleAreaSearchSuccess (area) {
      this.areaSearch.areaVisible = false
      console.log(area)
      this.form.setFieldsValue({
        areaName: area.text || area.id
      })
      this.areaSearch.areaId = area.id
    },
    removeTax (k) {
      const { form } = this
      // can use data-binding to get
      const keys = form.getFieldValue('taxInfos')
      // We need at least one passenger
      if (keys.length === 1) {
        return
      }

      // can use data-binding to set
      form.setFieldsValue({
        taxInfos: keys.filter(key => key !== k)
      })
    },
    addTax () {
      const { form } = this
      // can use data-binding to get
      const keys = form.getFieldValue('taxInfos')
      const nextKeys = keys.concat(id++)
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        taxInfos: nextKeys
      })
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this)
    this.form.getFieldDecorator('taxInfos', { initialValue: [0], preserve: true })
  },
  watch: {
    shopAddVisiable () {

    }
  }
}
</script>
<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
